

/**
 * 小游戏平台SDK工具封装，目前只支持微信和抖音平台
 */
export namespace MiniGameSdk {

    interface ISize {
        width: number;
        height: number;
    }

    export interface IPosition {
        top: number;
        left: number;
    }

    enum EPlatform {
        /**
         * 当前开发环境
         */
        DEVELOP,

        /**
         * 微信小游戏环境
         */
        WECHAT,

        /**
         * 抖音小游戏环境
         */
        BYTEDANCE,
    }

    export function isWechat(): boolean {
        //@ts-ignore
        return window.wx !== null && window.wx !== undefined;
    }

    export function isBytedance(): boolean {
        //@ts-ignore
        return window.tt !== null && window.tt !== undefined;
    }

    /**
     * 获得平台标识。只支持微信、抖音和开发环境。
     * @returns 
     */
    function getPlatformType(): EPlatform {
        if (isWechat()) {
            return EPlatform.WECHAT;
        } else if (isBytedance()) {
            return EPlatform.BYTEDANCE;
        } else {
            return EPlatform.DEVELOP;
        }
    }

    function getPlatformSystemWindowSize(): ISize {
        let platform = getPlatformType();
        let systemInfo: any;
        if (platform === EPlatform.WECHAT) {
            // @ts-ignore
            systemInfo = wx.getSystemInfoSync();
        } else if (platform === EPlatform.BYTEDANCE) {
            // @ts-ignore
            systemInfo = tt.getSystemInfoSync();
        }

        let windowSize: ISize = { width: 0, height: 0 };
        if (systemInfo) {
            windowSize.width = systemInfo.windowWidth;
            windowSize.height = systemInfo.windowHeight;
        }

        return windowSize;
    }

    /**
     * 插屏广告。微信抖音都支持！
     */
    class ADInterstitial {
        private _adUid: string;
        private _interstitialAd: any;

        get aduid() {
            return this._adUid;
        }

        /**
         * 插屏广告。只需要显示即可，让用户自主关闭。
         * @param adUid 广告UID，后端配置
         */
        constructor(adUid: string) {
            this._adUid = adUid;
        }

        /**
         * 显示插屏广告
         * @returns 
         */
        show() {
            let platform = getPlatformType();
            if (platform === EPlatform.DEVELOP) {
                this._interstitialAd = null;
                return;
            }

            // @ts-ignore
            if (isWechat() && !wx.createInterstitialAd) {
                console.warn('wechat unsupport interstitial AD!');
                this._interstitialAd = null;
                return;
            }

            // @ts-ignore
            if (isBytedance() && !tt.createInterstitialAd) {
                console.warn('bytedance unsupport interstitial AD!');
                this._interstitialAd = null;
                return;
            }

            // 显示的时候才加载
            if (this._interstitialAd) {
                this._interstitialAd.load(); // 会在onLoad里面自动show
            } else {
                if (platform === EPlatform.WECHAT) {
                    // @ts-ignore
                    this._interstitialAd = wx.createInterstitialAd({ adUnitId: this._adUid });
                } else if (platform === EPlatform.BYTEDANCE) {
                    // @ts-ignore
                    this._interstitialAd = tt.createInterstitialAd({ adUnitId: this._adUid });
                } else {
                    this._interstitialAd = null;
                }

                this._interstitialAd?.onLoad(() => {
                    console.log('load interstitial ad success');
                    this._interstitialAd.show().catch((err: any) => {
                        console.log('catch interstitial ad error:', err);
                    });
                });

                this._interstitialAd?.onError((err: any) => {
                    console.log('interstitial ad on error:', err);
                });
            }
        }

        /**
         * 销毁插屏广告
         */
        destory() {
            this._interstitialAd?.destroy();
        }
    }

    /**
     * 横幅广告。微信抖音都支持！
     */
    class ADBanner {
        private _adUid: string;
        private _bannerAd: any;

        get aduid() {
            return this._adUid;
        }

        /**
         * 抖音和微信都支持
         * 横幅广告。预估宽度默认为300，预估高度为140。如果你不确定就按默认值来。
         * @param adUid 广告UID，后端配置
         * @param isTop 是否在屏幕顶部展示。内部会自动居中计算位置。
         * @param bannerWidth 横幅广告的预估宽度。默认300
         * @param autoShow 广告加载完成后是否立刻显示，默认为不显示
         */
        constructor(adUid: string, position: boolean | IPosition, bannerWidth: number = 300, autoShow: boolean = false) {
            this._adUid = adUid;
            this.create(autoShow, bannerWidth, position); // 默认300比较合适
        }

        private create(autoShow: boolean, bannerWidth: number, position: boolean | IPosition) {
            let platform = getPlatformType();
            if (platform === EPlatform.DEVELOP) {
                this._bannerAd = null;
                return;
            }

            this.destroy();

            let windowSize = getPlatformSystemWindowSize();

            let height = bannerWidth * 0.4;
            let top = 0, left = 0;

            if (typeof position === "boolean") {
                left = (windowSize.width - bannerWidth) / 2
                top = position ? 5 : (windowSize.height - height);
            } else {
                left = position.left;
                top = position.top;
            }

            let params = {
                adUnitId: this._adUid,
                adIntervals: 30,// 自动刷新频率不能小于30秒
                style: { left: left, top: top + 20, width: bannerWidth }
            }

            if (platform === EPlatform.WECHAT) {
                // @ts-ignore
                this._bannerAd = wx.createBannerAd(params);
            } else if (platform === EPlatform.BYTEDANCE) {
                // @ts-ignore
                this._bannerAd = tt.createBannerAd(params);
            } else {
                this._bannerAd = null;
            }

            this._bannerAd?.onError((err: any) => {
                console.log('ad banner error:', err);
            });

            this._bannerAd?.onLoad(() => {
                autoShow && this._bannerAd.show();
            });
        }

        /**
         * 显示横幅广告
         */
        show() {
            this._bannerAd?.show();
        }

        /**
         * 隐藏横幅广告
         */
        hide() {
            this._bannerAd?.hide();
        }

        /**
         * 销毁横幅广告
         */
        destroy() {
            this._bannerAd?.destroy();
        }
    }

    /**
     * 原生模板广告。微信支持，抖音不支持！
     */
    class ADCustom {
        private _adUid: string;
        private _customAd: any;

        get aduid() {
            return this._adUid;
        }
        /**
         * 由于原生模板广告在微信服务后端可以定制宽度大小，个数，缩放比例等，所以位置调整要根据设置的宽度来定。抖音不支持！
         * @param adUid 广告UID，后端配置
         * @param top 从左上角开始，距离屏幕顶部的距离。注意：这个数据为设备屏幕宽度width。如果需要获取屏幕的像素，需要乘以设备像素比Pixel-Ratio，例如iPhone 13 Pro的Pixel-Ratio为3，像素为Width*3。
         * @param left 从左上角开始，距离屏幕最左边的距离。注意：这个数据为设备屏幕宽度width。如果需要获取屏幕的像素，需要乘以设备像素比Pixel-Ratio，例如iPhone 13 Pro的Pixel-Ratio为3，像素为Width*3。
         * @param scale 原生模板广告的尺寸，默认为1，即100%。此值在微信服务后端广告中获得，默认为100%，目前有100%，90%，80%三种，一般情况不用修改。若有修改，记得传入值，例如90%就传入0.9。
         */
        constructor(adUid: string, top: number = 0, left: number = 0, scale: number = 1.0) {
            this._adUid = adUid;
            this.createCustomAd(top, left, scale);
        }

        private createCustomAd(top: number, left: number, scale: number) {
            let platform = getPlatformType();
            if (platform === EPlatform.DEVELOP || platform === EPlatform.BYTEDANCE) {
                this._customAd = null;
                console.log('develop or bytedance env not support custom Ad:', platform);
                return;
            }

            this.destroy();

            // @ts-ignore
            this._customAd = wx.createCustomAd({
                adUnitId: this._adUid,
                style: { left: left, top: top, fixed: true } // fixed这个参数只适用于小程序环境
            });

            this._customAd?.onError((err: any) => {
                console.log('ad custom error:', err);
            });
        }

        /**
         * 显示原生模板广告
         */
        show() {
            this._customAd?.show();
        }

        /**
         * 隐藏原生模板广告
         */
        hide() {
            this._customAd?.hide();
        }

        /**
         * 销毁原生模板广告
         */
        destroy() {
            this._customAd?.destroy();
        }
    }


    /**
     * 视频广告用户点击行为结果
     */
    export enum EAdVideoResult {
        /**
         * 用户看完了广告，游戏可发放奖励。
         */
        ACCEPT,

        /**
         * 用户中途关闭了广告，即未看完状态。不可发放奖励。
         */
        REJECT,

        /**
         * 广告组件内部发生了错误。不可发放奖励。
         */
        ERROR,
    }

    /**
     * 激励视频广告。微信和抖音都支持！
     */
    class ADVideo {
        private _adUid: string;
        private _videoAd: any = null;

        get aduid() {
            return this._adUid;
        }

        /**
         * 激励视频广告
         * @param adUid 广告UID，后端配置
         */
        constructor(adUid: string) {
            this._adUid = adUid;
        }

        /**
         * 由于微信和抖音视频广告机制不同，微信可以看的视频广告个数只有0和1个，抖音平台则可以看0~maxVideoCount
         * @param onResult 两个参数：第一个res是EAdVideoResult定义，第二count是用户看了多少个视频广告。
         * @param target onResult的拥有者
         * @param maxVideoCount 可以连续看最大视频个数，可最大化商业效率。默认为3个。
         * @returns 
         */
        show(onResult: (res: EAdVideoResult, count: number) => void, target?: any, maxVideoCount: number = 3): void {
            let callback = (state: EAdVideoResult, count: number) => {
                onResult?.call(target, state, count);
            }

            let platform = getPlatformType();
            if (platform === EPlatform.DEVELOP) {
                callback(EAdVideoResult.ACCEPT, 1);
                this._videoAd = null;
                return;
            }

            let onAdVideoClosed = (res: any) => {
                this._videoAd?.offClose(onAdVideoClosed);// 必须注销掉上一次的回调，否则可能产生多次回调
                // 用户点击关闭广告按钮，基础库版本<2.1.0时，res是undefined
                if (platform === EPlatform.WECHAT) {
                    if (res && res.isEnded || res === undefined) {
                        callback(EAdVideoResult.ACCEPT, 1);
                    } else {
                        callback(EAdVideoResult.REJECT, 0);
                    }
                } else if (platform === EPlatform.BYTEDANCE) {
                    let resConverted = res as { isEnded: boolean, count: number };
                    if (resConverted && resConverted.count > 0) {
                        callback(EAdVideoResult.ACCEPT, resConverted.count);
                    } else {
                        callback(EAdVideoResult.REJECT, 0);
                    }
                }
            }

            this._videoAd?.offClose(onAdVideoClosed);// 注销掉上一次的回调，否则可能产生多次回调

            if (platform === EPlatform.WECHAT) {
                // @ts-ignore
                this._videoAd = wx.createRewardedVideoAd({
                    adUnitId: this._adUid
                });
            } else if (platform === EPlatform.BYTEDANCE) {
                // @ts-ignore
                this._videoAd = tt.createRewardedVideoAd({
                    adUnitId: this._adUid,
                    multiton: true,
                    multitonRewardMsg: ['多1次奖励', '再多一次奖励', '再多一次奖励'],
                    multitonRewardTimes: maxVideoCount,
                });
            } else {
                this._videoAd = null;
            }

            this._videoAd?.onLoad(() => {
                console.log('ad video load success');
            });

            this._videoAd?.onError((err: { errMsg: string, errCode: number }) => {
                console.log('ad video error:', err);
                callback(EAdVideoResult.ERROR, 0);
            });

            this._videoAd?.onClose(onAdVideoClosed);

            this._videoAd?.show().catch(() => {
                this._videoAd?.load().then(() =>
                    this._videoAd?.show()).catch((err: { errMsg: string, errCode: number }) => {
                        console.log('catch video ad error:', err);
                        callback(EAdVideoResult.ERROR, 0);
                    });
            });
        }

        /**
         * 销毁视频广告
         */
        destory() {
            this._videoAd?.destory();
        }
    }

    /**
     * 横幅广告的位置
     */
    export enum EAdBannerLocation {
        /**
         * 屏幕顶部
         */
        TOP,

        /**
         * 屏幕底部
         */
        BOTTOM,
    }

    /**
     * 广告管理器
     */
    export class AdvertManager {

        private static _instance: AdvertManager;

        static get instance(): AdvertManager {
            if (!AdvertManager._instance) {
                AdvertManager._instance = new AdvertManager();
            }
            return AdvertManager._instance;
        }

        private _videoAd: ADVideo;
        private _interstitialAd: ADInterstitial;
        private _bannerAd: ADBanner;
        private _customAd: ADCustom;
        public blnFromShare: boolean = false;
        private constructor() {

        }

        /**
         * 预加载横幅广告，不会显示。只有你在调用showBanner时才会显示。
         * 可重复调用，但是会销毁上一次的实例。一般情况，全局有一个就行了，太多占用内存，而且没必要。
         * @param adUid 广告UID
         * @param location 位置有两种情况：1、可以传入枚举值，默认上方; 2、可以自定义位置传入IPosition，注意IPosition中的top和left跟平台的top,left是一致（没有乘以设备像素比ratio），需要开发者自己调试位置
         * @param scale 默认为跟屏幕一样的宽度，可以通过设置缩放比例来调整大小。当然，平台有规定最大或最小宽度，函数内部会自动计算。
         */
        public loadBanner(adUid: string, location: EAdBannerLocation | IPosition = EAdBannerLocation.TOP, scale: number = 1.0) {
            this._bannerAd?.destroy();
            let windowSize: ISize = getPlatformSystemWindowSize();
            // 当 style.width 小于 300 时，会取作 300。 当 style.width 大于屏幕宽度时，会取作屏幕宽度。
            let width = windowSize.width * scale;
            width = width < 300 ? 300 : width; // 最小值矫正
            width = width > windowSize.width ? windowSize.width : width; //最大值矫正
            width = 300;
            this._bannerAd = typeof location === 'number' ? new ADBanner(adUid, location === EAdBannerLocation.TOP, width, false) : new ADBanner(adUid, location, width, false);
        }

        /**
         * 显示横幅广告
         */
        public showBanner() {
            if (this._bannerAd) {
                this._bannerAd.show();
            } else {
                console.error('MiniGameSDK: banner is null, you must call loadBanner(...) first!');
            }
        }

        /**
         * 隐藏横幅广告
         */
        public hideBanner() {
            this._bannerAd?.hide();
        }

        /**
         * 弹出插屏广告
         * @param adUid 广告单元id
         */
        public showInterstitial(adUid: string) {
            if (this._interstitialAd && this._interstitialAd.aduid === adUid) {
                this._interstitialAd.show();
            } else {
                this._interstitialAd?.destory();
                this._interstitialAd = new ADInterstitial(adUid);
                this._interstitialAd.show();
            }
        }

        /**
         * 加载原生模板广告，不会显示。只有你在调用showCustom时才会显示。
         * 由于原生模板广告在微信服务后端可以定制宽度大小，个数，缩放比例等，所以位置调整要根据设置的宽度来定。抖音不支持本函数，会调用无效！
         * @param adUid 广告ID
         * @param location 位置有两种情况：1、可以传入枚举值，默认上方; 2、可以自定义位置传入IPosition，注意IPosition中的top和left跟平台的top,left是一致（没有乘以设备像素比ratio），需要开发者自己调试位置
         * @param scale 缩放比例，默认是1，即不缩放         
         */
        public loadCustom(adUid: string, location: IPosition = { top: 0, left: 0 }, scale: number = 1) {
            this._customAd?.destroy();
            this._customAd = new ADCustom(adUid, location.top, location.left, scale);
        }

        public loadCustomOne1(adUid: string, location: IPosition = { top: 0, left: 0 }, scale: number = 1) {
            // this._customAd?.destroy();
            // this._customAd = new ADCustom(adUid, location.top, location.left, scale);
        }

        public loadCustomOne2(adUid: string, location: IPosition = { top: 0, left: 0 }, scale: number = 1) {
            // this._customAd?.destroy();
            // this._customAd = new ADCustom(adUid, location.top, location.left, scale);
        }

        public loadCustomOne3(adUid: string, location: IPosition = { top: 0, left: 0 }, scale: number = 1) {
            // this._customAd?.destroy();
            // this._customAd = new ADCustom(adUid, location.top, location.left, scale);
        }

        public loadCustomOne4(adUid: string, location: IPosition = { top: 0, left: 0 }, scale: number = 1) {
            // this._customAd?.destroy();
            // this._customAd = new ADCustom(adUid, location.top, location.left, scale);
        }

        /**
         * 显示原生模板广告
         */
        public showCustom() {
            if (this._customAd) {
                this._customAd.show();
            } else {
                console.error('MiniGameSDK: custom is null, you must call loadCustom(...) first!');
            }
        }

        /**
         * 隐藏原生模板广告
         */
        public hideCustom() {
            this._customAd?.hide();
        }

        showCustomOne2() {

        }

        showCustomOne3() {

        }

        /**
         * 由于微信和抖音视频广告机制不同，微信可以看的视频广告个数只有0和1个，抖音平台则可以看0~maxVideoCount
         * @param adUid 广告ID。如果与上一次UID不同，则内部会重新创建实例。开发者完全不用关心这个细节。
         * @param onVideoResult 两个参数：第一个res是EAdVideoResult定义，第二count是用户看了多少个视频广告。 
         * @param target onVideoResult的拥有者
         * @param maxVideoCount 最大视频个数。默认是3，仅对抖音平台生效。微信平台看完视频count的结果永远是1或0
         */
        public showVideo(adUid: string, onVideoResult: (res: EAdVideoResult, count: number) => void, target?: any, maxVideoCount: number = 3) {
            //onVideoResult(MiniGameSdk.EAdVideoResult.ACCEPT,0)
            if (this._videoAd && this._videoAd.aduid === adUid) {
                this._videoAd.show(onVideoResult, target, maxVideoCount);
            } else {
                this._videoAd?.destory();
                this._videoAd = new ADVideo(adUid);
                this._videoAd.show(onVideoResult, target, maxVideoCount);
            }
        }

        /**
         * 销毁内部所有实例，清空内存
         */
        public destroyAll() {
            this._bannerAd?.destroy();
            this._bannerAd = null;

            this._interstitialAd?.destory();
            this._interstitialAd = null;

            this._videoAd?.destory();
            this._videoAd = null;

            this._customAd?.destroy();
            this._customAd = null;
        }
    }

    /**
     * 振动类型
     */
    export enum EVirbrateType {
        /**
         * 短振动
         */
        SHORT,

        /**
         * 长振动
         */
        LONG
    }

    /**
     * 平台常用API合集
     */
    export class API {
        private static _loginCode: string = null;
        private static _loginAnonymousCode: string = null;
        private static _hasInitWechatCloudFunction: boolean = false;

        private static _onShowCallback: any = null;
        private static _lastShareTime = 0;
        private static _failedShareCount = 0;

        private static autoCheckCallback(onWechat: () => void, onBytedance: () => void) {
            switch (getPlatformType()) {
                case EPlatform.DEVELOP: console.log('develop env not support!'); break;
                case EPlatform.WECHAT: onWechat?.(); break;
                case EPlatform.BYTEDANCE: onBytedance?.(); break;
                default: break
            }
        }

        /**
         * 分享app给朋友，微信小游戏分享是没有onSuccess回调的。
         * @param title 标题
         * @param description 细节描述信息 
         * @param imageUrl 图片地址
         * @param query 查询信息
         * @param onSuccess 成功回调。微信分享是不会返回的。
         */
        // static shareAppToFriends(title: string, description: string = '', imageUrl?: string, query?: string, onSuccess?: () => void) {
        //     this.autoCheckCallback(
        //         () => {
        //             try {
        //                 //@ts-ignore
        //                 wx.shareAppMessage({
        //                     title: title,
        //                     imageUrl: imageUrl,
        //                     query: query,
        //                 });
        //             } catch (err) {
        //                 console.log(`share faild: ${err}`);
        //             }
        //         },

        //         () => {
        //             //@ts-ignore
        //             tt.shareAppMessage({
        //                 title: title,
        //                 desc: description,
        //                 imageUrl: imageUrl ?? '',
        //                 query: query ?? '',
        //                 success(res: any) {
        //                     console.log('share success:', res);
        //                     onSuccess?.();
        //                 },
        //                 fail(res: any) {
        //                     console.log('share fail:', res);
        //                 }
        //             });
        //         });
        // }

        static shareAppToFriendsNew(title: string, description: string = '', imageUrl?: string, query?: string, onSuccess?: (success: boolean) => void) {
            if (window["tt"]) {
                //@ts-ignore
                tt.shareAppMessage({
                    title: title,
                    desc: description,
                    imageUrl: imageUrl ?? '',
                    query: query ?? '',
                    success(res: any) {
                        console.log('share success:', res);
                        onSuccess?.(true);
                    },
                    fail(res: any) {
                        console.log('share fail:', res);
                        onSuccess?.(false);
                    }
                });
            } else if (window["wx"]) {
                this._onShowCallback = () => {
                    window["wx"].offShow(this._onShowCallback);
                    const currentTime = Date.now();
                    if (onSuccess) {
                        if (this._failedShareCount < 2) {
                            if (currentTime - this._lastShareTime > 2000) {
                                if (Math.random() < 0.3) {
                                    onSuccess(false);
                                    API.showToast("分享失败,请分享至群聊");
                                    this._failedShareCount++;
                                } else {
                                    API.showToast("分享成功");
                                    onSuccess(true);
                                }
                            } else {
                                this._failedShareCount++;
                                onSuccess(false);
                                API.showToast("分享失败,请重新分享");
                            }
                        } else {
                            API.showToast("分享成功");
                            this._failedShareCount = 0;
                            onSuccess(true);
                        }
                    }
                }
                window["wx"].onShow(this._onShowCallback);
                this._lastShareTime = Date.now();
                window["wx"].shareAppMessage({
                    imageUrlId: "",
                    imageUrl: "https://mmocgame.qpic.cn/wechatgame/bSAKPPBBQFUN44PHyDL1mOY72Z1pA2eT0x3QtvGFxdL0ZPob1wej1Dy32ttBtt5y/0",
                    title: "你敢来吃我吗"
                });
            }
        }

        /**
         * 显示提示信息
         * @param title 标题
         * @param duration 时长（单位：秒）
         * @returns 
         */
        static showToast(title: string, duration: number = 2) {
            this.autoCheckCallback(
                () => {
                    // @ts-ignore
                    wx.showToast({
                        title: title,
                        icon: 'success',
                        duration: duration * 1000
                    });
                },

                () => {
                    //@ts-ignore
                    tt.showToast({
                        title: title,
                        duration: duration * 1000,
                        success(res: any) {
                            console.log(`${res}`);
                        },
                        fail(res: any) {
                            console.log(`showToast调用失败`);
                        },
                    });
                })
        }

        /**
         * 设备震动效果，默认为短震动。注意：可能一些机型不会生效，具体看平台方的说明
         * @param type MiniGameSdk.API.EVirbrateType
         */
        static vibrate(type: EVirbrateType = EVirbrateType.SHORT) {
            this.autoCheckCallback(
                () => {
                    switch (type) {
                        case EVirbrateType.SHORT:
                            //@ts-ignore
                            wx.vibrateShort({
                                success(res: any) {
                                    console.log('vibrate success:', res);
                                },
                                fail(res: any) {
                                    console.log('vibrateShort failed', res);
                                },
                            });
                            break;
                        case EVirbrateType.LONG:
                            //@ts-ignore
                            wx.vibrateLong({
                                success(res: any) {
                                    console.log('vibrate success', res);
                                },
                                fail(res: any) {
                                    console.log(`vibrateLong failed`, res);
                                },
                            });
                            break;
                        default:
                            break;
                    }
                },

                () => {
                    switch (type) {
                        case EVirbrateType.SHORT:
                            //@ts-ignore
                            tt.vibrateShort({
                                success(res: any) {
                                    console.log('vibrate success:', res);
                                },
                                fail(res: any) {
                                    console.log('vibrateShort failed', res);
                                },
                            });
                            break;
                        case EVirbrateType.LONG:
                            //@ts-ignore
                            tt.vibrateLong({
                                success(res: any) {
                                    console.log('vibrate success', res);
                                },
                                fail(res: any) {
                                    console.log(`vibrateLong failed`, res);
                                },
                            });
                            break;
                        default:
                            break;
                    }
                });
        }
        static gameClubButton: any = null;
        static createWxGameHub(posX: number, posY: number) {
            if (cc.sys.platform != cc.sys.WECHAT_GAME) {
                return;
            }
            let windowSize = cc.view.getVisibleSize();
            let leftRatio = posX / windowSize.width;
            let topRatio = posY / windowSize.height;
            //@ts-ignore
            const systemInfo = wx.getSystemInfoSync();//立即获取系统信息
            const screenWidth: number = systemInfo.screenWidth;//屏幕宽
            const screenHeight: number = systemInfo.screenHeight;//屏幕高
            console.log("屏幕宽:" + screenWidth)
            console.log("屏幕高:" + screenHeight)
            let leftPos = systemInfo.windowWidth * leftRatio;
            let topPos = systemInfo.windowHeight * (topRatio);
            //@ts-ignore
            MiniGameSdk.API.gameClubButton = wx["createGameClubButton"]({
                icon: 'light',//green dark white light
                style: {
                    left: 10,//leftPos - 20,//5,info.windowWidth - 50
                    top: 60,//topPos - 50,//150,
                    width: 40,
                    height: 40,
                    backgroundColor: '#00000000',//最后两位为透明度
                }
            })
        }

        /**
         * 重启小游戏
         */
        static reboot() {
            this.autoCheckCallback(
                () => {
                    //@ts-ignore
                    wx.restartMiniProgram({
                        success: () => {
                            console.log('restart success');
                        },

                        fail: () => {
                            console.log('restart failed');
                        }
                    })
                },

                () => {
                    try {
                        // @ts-ignore
                        tt.restartMiniProgramSync();
                    } catch (error) {
                        console.log(`restartMiniProgramSync`, error);
                    }
                });
        }

        /**
         * 退出小游戏
         */
        static exit() {
            this.autoCheckCallback(
                () => {
                    //@ts-ignore
                    wx.exitMiniProgram({
                        success: () => {
                            console.log('exit success');
                        },
                        fail: () => {
                            console.log('exit failed');
                        }
                    })
                },

                () => {
                    // @ts-ignore
                    tt.exitMiniProgram({
                        success(res: any) {
                            console.log("exit success:", res?.data);
                        },
                        fail(res: any) {
                            console.log("exit fail:", res?.errMsg);
                        },
                    });
                });
        }
        static  randomIntNum(min: number, max: number): number {
            return Math.round(MiniGameSdk.API.randomFloatNum(min, max));
        }
        static randomFloatNum(min: number, max: number): number {
            let seed = Date.now();
            max = max || 0;
            min = min || 0;
            max = Math.max(max, min);
            min = Math.min(max, min);
            seed = (9301 * seed + 49297) % 233280;
            return min + (seed / 233280) * (max - min);
        }
        /**
         * 显示转发按钮。通常在刚进入游戏的时候调用。
         * 主要是打开平台“...”这个按钮里面的分享菜单，一般默认是关闭的，需要调用这个函数打开。可以让用户分享你的游戏入口。
         */
        static showShareMenu() {
            this.autoCheckCallback(
                () => {
                    //@ts-ignore
                    wx.showShareMenu({
                        withShareTicket: true,
                        menus: ['shareAppMessage', 'shareTimeline'],
                        success: () => { },
                        fail: () => { },
                        complete: () => { }
                    });
                    let titles = [
                        "魔性小游戏，无需下载，点击即玩！",
                        "谁设计的第二关，完全过不去啊！",
                        "解压，实在是太解压了！",
                        "我老公秒过第二关！你行不行呀",
                        "听哥一句劝，这游戏你别碰，怕你把握不住！",
                        "这关能不能一次过就看你了",
                        "有本事你来把第二关过了呀[旺柴]",
                        "该不会有人过不了第二关吧？",
                        "能过第二关的人，智商都不低于150[嘿哈]",
                        "谁能过去第2关我就服她！[左哼哼]",
                        "饭前玩一把，开心又解压[机智][呲牙]",
                        "笑死，老婆来了也过不了第二关[呲牙]",
                        "谁能过关我就服她！",
                        "据说这游戏仅0.2%的人能通过第二关，你敢来试...",
                        "这游戏你能过了第二关，算你厉害！"
                    ]
                    let imageUrls = [
                        "https://mmocgame.qpic.cn/wechatgame/oxByTG5ibhWjHwM4OPKyhf5vJSZictFSZdspMiccic3uo3tYdPpNnFokzC19MYLQUGcP/0",
                        "https://mmocgame.qpic.cn/wechatgame/kVz9DdkicmVg8tFWHCV80uNTaH4tIuxfZpAcyz2iaSSY7rmEOM7wsCgHgXWjjN1uhU/0",
                        "https://mmocgame.qpic.cn/wechatgame/4Nvoic6orqLonquA5DKR5MzLYNnSpicqD2XdO45MHY10bibsMFusmPhpfibJ1WXMXHhA/0",
                        "https://mmocgame.qpic.cn/wechatgame/icwicFxXAiaFTyHWWGlMC9PTG1WeTS2f4UJzI1SFBhk2SUyLInMmb9drX3XMxGUQ1KL/0",
                        "https://mmocgame.qpic.cn/wechatgame/ibVyxNISGA75TsSGaOmBp3dqSWD4yd9lznHe0Qq0ZG6DcTOuDllmHSV2dhA5300p9/0",
                        "https://mmocgame.qpic.cn/wechatgame/cmT3ulLfYrlcDWiakgibawib4aUiaWRuy2eEV64qrUO00PiaPbzacNPIlBjOIia6B1AKxC/0",
                        "https://mmocgame.qpic.cn/wechatgame/XqtEbkfpjbQ7LEpmDjTl1z4hzeUNNCIdRckDZuhYy7yrcLQZ9vaLIdDrXfTQLG2t/0",
                        "https://mmocgame.qpic.cn/wechatgame/WohhvAj4g78IJY2Yn64f6TsjY25nCNlibHIfHH8AlnmJuCsS51GySNHsbRzveibicicG/0"
                    ]
                    //右上角点击3个点,分享给好友的设置 用户点击了“转发”按钮
                    window["wx"]["onShareAppMessage"](() => {
                        return {
                            title: titles[MiniGameSdk.API.randomIntNum(0, titles.length - 1)],
                            imageUrl: imageUrls[MiniGameSdk.API.randomIntNum(0, imageUrls.length - 1)], // 图片 URL
                            query: 'shareid=100' //分享参数，别人打开的时候能取到
                        }
                    })
                    //分享到朋友圈的设置，设置分享图片、标题，若不设置，则会以小游戏名称作为分享标题，以小游戏 logo 作为分享图片。
                    window["wx"]["onShareTimeline"](() => {
                        return {
                            title: titles[MiniGameSdk.API.randomIntNum(0, titles.length - 1)],
                            imageUrl: imageUrls[MiniGameSdk.API.randomIntNum(0, imageUrls.length - 1)], // 图片 URL
                            query: 'shareid=200' //分享参数，别人打开的时候能取到
                        }
                    })
                    window["wx"]["onShow"]((res) => {
                        console.log("onShow")
                        if (!MiniGameSdk.AdvertManager.instance.blnFromShare) {
                            MiniGameSdk.AdvertManager.instance.showInterstitial('adunit-203b3a122ff3e583');
                        } else {
                            MiniGameSdk.AdvertManager.instance.blnFromShare = false;
                        }
                        cc.audioEngine.pauseMusic();
                        cc.audioEngine.pauseAllEffects();
                        cc.audioEngine.resumeMusic();
                        cc.audioEngine.resumeAllEffects();
                    })
                },

                () => {
                    //@ts-ignore
                    tt.showShareMenu({
                        success(res: any) {
                            console.log("show menu is showing");
                        },
                        fail(err: any) {
                            console.log("showShareMenu:", err.errMsg);
                        },
                        complete(res: any) {
                            console.log("showShareMenu complete");
                        },
                    });
                });
        }

        /**
         * 微信小游戏：跳转到另外一款小游戏
         * 抖音小游戏：跳转到指定的视频界面
         * @param targetId 微信小游戏appid或者视频界面
         */
        static navigateTo(targetId: string, onSuccess?: () => void) {
            this.autoCheckCallback(
                () => {
                    // @ts-ignore
                    wx.navigateToMiniProgram({
                        appId: targetId,
                        extraData: {
                            foo: 'bar'
                        },
                        envVersion: 'develop',
                        success(res: any) {
                            onSuccess?.();
                        }
                    });
                },

                () => {
                    // @ts-ignore
                    tt.navigateToVideoView({
                        videoId: targetId,
                        success: (res: any) => {
                            onSuccess?.();
                        },
                        fail: (err: any) => {
                            console.log("bytedance navigateToVideoView fail", err);
                        },
                    });
                });
        }

        /**
         * 小游戏平台登录功能。微信返回code，抖音返回code和anonymousCode。用于登录的凭证，需要把这个code传回你的服务器程序中去调用code2Session
         * @param callback (code, anonymousCode) 第一个参数为code，微信和抖音都支持；第二个参数为匿名设备ID，仅抖音支持，失败都返回null
         */
        static login(callback: (code: string, anonymousCode: string) => void) {
            let platform = getPlatformType();

            let loginPlatform = () => {
                if (platform === EPlatform.WECHAT) {
                    //@ts-ignore
                    wx.login({
                        success: (res: { code: any; errMsg: any; }) => {
                            if (res.code) {
                                API._loginCode = res.code;
                                API._loginAnonymousCode = null;
                                callback?.(API._loginCode, API._loginAnonymousCode);
                            } else {
                                console.log('login error:', res.errMsg)
                            }
                        },

                        fail: () => {
                            API._loginCode = null;
                            API._loginAnonymousCode = null;
                            callback?.(API._loginCode, API._loginAnonymousCode);
                            console.log('login fail')
                        }
                    });
                } else if (platform === EPlatform.BYTEDANCE) {
                    //@ts-ignore
                    tt.login({
                        force: true,
                        success(res: any) {
                            console.log(`login ${res.code} ${res.anonymousCode}`);
                            if (res.code) {
                                API._loginCode = res.code?.toString();
                                API._loginAnonymousCode = res.anonymousCode?.toString();
                                callback?.(API._loginCode, API._loginAnonymousCode);
                            } else {
                                console.log('login error:', res.errMsg)
                            }
                        },
                        fail(res: any) {
                            API._loginCode = null;
                            API._loginAnonymousCode = null;
                            callback?.(API._loginCode, API._loginAnonymousCode);
                            console.log(`login fail`, res);
                        },
                    });
                } else {
                    API._loginCode = null;
                    API._loginAnonymousCode = null;
                    callback?.(API._loginCode, API._loginAnonymousCode);
                    console.log('not mini game platform, login codes are all null');
                }
            }

            if (!API._loginCode) {
                loginPlatform();
            } else {
                if (platform === EPlatform.WECHAT) {
                    //@ts-ignore
                    wx.checkSession({
                        success() {
                            console.log(`session is valid, use current code:`, API._loginCode);
                            callback?.(API._loginCode, API._loginAnonymousCode);
                        },
                        fail() {
                            console.log(`session expired`);
                            loginPlatform();
                        }
                    });
                } else if (platform === EPlatform.BYTEDANCE) {
                    //@ts-ignore
                    tt.checkSession({
                        success() {
                            console.log(`session is valid, user current code: ${API._loginCode}, ${API._loginAnonymousCode}`);
                            callback?.(API._loginCode, API._loginAnonymousCode);
                        },
                        fail() {
                            console.log(`session expired`);
                            loginPlatform();
                        },
                    });

                } else {
                    console.log('not mini game platform, login null');
                    callback?.(null, null);
                }
            }
        }

        /**
         * 调用微信云函数。由于参数需要自定义，所以为any，需要自行解释。函数只完成通道和处理一场的作用
         * @param callback 返回云函数调用结果。需要检查返回参数是否为空，失败的时候为空
         * @param name 云函数的名字
         * @param data 云函数的内容
         */
        static callWechatCloudFunction(callback: (res: any) => void, name: string, data: {}) {
            if (!isWechat()) {
                console.log('Not wechat platform, not support callWechatCloudFunction');
                return;
            }

            this.login((code: string, anonymousCode: string) => {
                if (!API._hasInitWechatCloudFunction) {
                    //@ts-ignore
                    wx.cloud.init();
                    API._hasInitWechatCloudFunction = true;
                }
                //@ts-ignore
                wx.cloud.callFunction({
                    name: name,
                    data: data,
                    success: (res: any) => callback?.(res),
                    fail: (err: any) => {
                        console.log('wechat cloud function error:', err);
                        callback?.(null);
                    }
                });
            });
        }

        /**
         * 存储用户信息，数据量不能大。可以考虑用于分数排行榜。用户之间可共享排行数据。
         * @param key 
         * @param value 
         */
        static setUserCloudStorage(key: string, value: string) {
            this.autoCheckCallback(
                () => {
                    // @ts-ignore
                    wx.setUserCloudStorage({
                        KVDataList: [{ key: key, value: value }],
                        success: () => console.log(`set cloud storage success:${key}, value:${value}`),
                        fail: (err: any) => console.log('set cloud storage error:', err)
                    });
                },

                () => {
                    // @ts-ignore
                    tt.setUserCloudStorage({
                        KVDataList: [{ key: key, value: value, }],
                        success: () => console.log(`set cloud storage success:${key}, value:${value}`),
                        fail: (err: any) => console.log('set cloud storage error:', err)
                    });

                }
            )
        }
    }

    /**
     * 抖音侧边栏专属接口
     */
    export class BytedanceSidebar {
        /**
         * 本游戏在抖音环境下启动监控，需要放在全局环境中，保证能第一时间启动。因为可能监听抖音失败（抖音小游戏官方的说明）！
         * @param onResult 包含一个boolean参数的函数
         * @param target 上述函数的拥有者，如果是类的成员函数，需要传入this。普通或匿名函数忽略即可。
         */
        static listenFromSidebar(onResult: (success: boolean) => void, target?: any) {
            if (!isBytedance()) {
                onResult?.call(target, false);
                return;
            }
            // @ts-ignore
            tt.onShow((res: any) => {
                console.log('onShow launch res:', res);
                if (res.scene === '021036') {
                    onResult?.call(target, true);
                    console.log('launch from sidebar');
                } else {
                    onResult?.call(target, false);
                    console.log('NOT launch from douyin sidebar!');
                }
            });

            // @ts-ignore
            let options = tt.getLaunchOptionsSync();
            if (options && options.scene === '021036') {
                onResult?.call(target, true);
            }
        }

        /**
         * 检测抖音侧边栏是否存在
         * @param onResult 包含一个boolean参数的函数
         * @param target 上述函数的拥有者，如果是类的成员函数，需要传入this。普通或匿名函数忽略即可。
         * @returns 
         */
        static checkSideBar(onResult: (success: boolean) => void, target?: any) {
            if (!isBytedance()) {
                onResult?.call(target, false);
                return;
            }

            //@ts-ignore
            tt.checkScene({
                scene: "sidebar",
                success: (res: any) => {
                    console.log("check scene success: ", res.isExist);
                    onResult?.call(target, <boolean>res.isExist);

                },
                fail: (res: any) => {
                    console.log("check scene fail:", res);
                    onResult?.call(target, false);
                }
            });
        }

        /**
         * 跳转到抖音侧边栏
         * @param onResult 包含一个boolean参数的函数
         * @param target 上述函数的拥有者，如果是类的成员函数，需要传入this。普通或匿名函数忽略即可。
         * @returns 
         */
        static navigateToSidebar(onResult: (success: boolean) => void, target?: any) {
            if (!isBytedance()) {
                console.log("not douyin platform!");
                onResult?.call(target, false);
                return;
            }

            // @ts-ignore
            tt.navigateToScene({
                scene: "sidebar",
                success: () => {
                    console.log("navigate success");
                    onResult?.call(target, true);
                },
                fail: (res: any) => {
                    console.log("navigate failed reason:", res);
                    onResult?.call(target, false);
                },
            });
        }
    }
}